package com.theydream.qeechain.ARcaught;

import java.util.List;

import android.location.Location;

import com.theydream.qeechain.globaldata.GlobalData;
import com.theydream.qeechain.globaldata.ItemListClass;
import com.theydream.qeechain.globaldata.definition.LocationData;

public class RandomEncounterLogic {
	public static LocationData getNextEncounter() {
		GlobalData data = GlobalData.getInstance();
		return getNextEncounter(data.getUserLantitude(),
				data.getUserLongtitude());
	}

	public static LocationData getNextEncounter(double userLatitude,
			double userLongitude) {

		List<LocationData> itemList = ItemListClass.getInstance().getItemList();
		double[] itemFacter = new double[itemList.size()];

		double factorSum = 0;

		int i = 0;
		for (LocationData locationData : itemList) {
			float[] distance = { 0.0f };
			Location.distanceBetween(userLatitude, userLongitude,
					locationData.getLat(), locationData.getLng(), distance);

			if (distance[0] == 0) {
				return itemList.get(i);
			}
			itemFacter[i] = locationData.getProbability() / distance[0];
			factorSum += itemFacter[i++];
		}

		double result = Math.random() * factorSum;

		for (i = 0; i < itemFacter.length; ++i) {
			result -= itemFacter[i];
			if (result <= 0) {
				return itemList.get(i);
			}
		}
		return null;
	}
}